from django.template import Context, loader
from django.core.context_processors import csrf
from django.template import RequestContext
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from games.models import Game
from games.models import ScheduledGame
from games.models import ScheduledGameForm
from games.models import Membership
from games.models import GameForm, SearchForm, PasswordForm
from games.models import GameForm
from django.shortcuts import render_to_response
from django.conf import settings
from django.forms.extras.widgets import SelectDateWidget
from django.http import Http404
from django.contrib.auth.models import User
from facebookconnect.models import FacebookProfile
import re

# Create your views here.
def home(request):
	joined_game = ''
	joined_game_label = ''
	search_post_success = ''
	pass_post_success = ''
    	search_form_error = ''
    	pass_form_error = ''
	user = ''
	USER_LOGGED_IN = ''
	logged_in_user = ''
	new_member = ''
	results = []
	city_query = request.GET.get('city', '') #searchform.cleaned_data['city']
	state_query = request.GET.get('state', '') #searchform.cleaned_data['state']
	game_query = request.GET.get('game', '') #searchform.cleaned_data['game']
	zip_query = request.GET.get('zipcode', '') #searchform.cleaned_data['zipcode']
	pass_query = request.GET.get('passwd', '')
	scheduled_game_unique = request.GET.get('a','')
	joinee_username = request.GET.get('b','')
	searchform = SearchForm()
	passform = PasswordForm()
	if request.user.is_authenticated():
		try:
			user = request.user.facebook_profile
			logged_in_user = User.objects.get(username__exact=user.facebook_id)
			
			#let user join game
			if scheduled_game_unique and joinee_username:
				new_member = Membership(user=User.objects.get(username=joinee_username), scheduled_game=ScheduledGame.objects.get(unique=scheduled_game_unique))  #add new member
				new_member.save()
				joined_game = 1
				joined_game_label = ScheduledGame.objects.get(unique__exact=scheduled_game_unique).label
				
		except:
			pass	

	if city_query and state_query and game_query:
		results = ScheduledGame.objects.filter(state__exact=state_query).distinct().filter(city__exact=city_query).distinct().filter(game__pk=game_query).distinct()
	elif zip_query and game_query:
		results = ScheduledGame.objects.filter(zipcode__exact=zip_query).distinct().filter(game__pk=game_query).distinct()
	else:
		results = []

    	return render_to_response('page_templates/home_template.html', 
		{		
			'logged_in_user': logged_in_user,
			'USER_LOGGED_IN': USER_LOGGED_IN,
			'joined_game' : joined_game,
			'joined_game_label' : joined_game_label,
			'user' : user,
			'searchform' : searchform,
			'passform': passform,
			'search_post_success' : search_post_success, 
			'search_form_error' : search_form_error,
			'results': results,
			'city_query': city_query,
			'state_query': state_query,
			'game_query': game_query,
			'zip_query': zip_query,
			'pass_query': pass_query,
		}, context_instance=RequestContext(request)
	)
#function for handling scheduling page
def scheduling(request):
	post_success = ''
    	form_error = ''
	user = ''
	USER_LOGGED_IN = ''
	scheduled_games = ''
	logged_in_user = ''
	cur_unique = ''
	deleted_game = request.GET.get('d', '')
 
	if request.user.is_authenticated():
		try:
			user = request.user.facebook_profile
			logged_in_user = User.objects.get(username__exact=user.facebook_id)
			scheduled_games = ScheduledGame.objects.filter(creator_username__exact=user.facebook_id)
			if deleted_game:	#handle delete request
				ScheduledGame.objects.get(unique__exact=deleted_game).members.clear()
				ScheduledGame.objects.get(unique__exact=deleted_game).delete()
		except:
			pass	

    	if request.method == 'POST':
		form = ScheduledGameForm(request.POST)
		temp_form = form.save(commit=False)
		temp_form.creator_username = user.facebook_id   #initializes creators username to be their facebook id 
		temp_form.unique = temp_form.creator_username + hash(temp_form.label) + hash(temp_form.date) + hash(temp_form.time)	#defines the unique label to be the creators facebook id plus the interger value of the label
		cur_unique = temp_form.unique
		if form.errors:
			form_error = 1
		elif form.is_valid:
			temp_form.save()
			member = Membership(user=User.objects.get(username=user.facebook_id), scheduled_game=ScheduledGame.objects.get(unique=cur_unique)) #defines membership and lets user join his own game
			member.save()
			post_success = 1
    	else:
		form = ScheduledGameForm()
    	return render_to_response('page_templates/schedule_template.html', 
		{		
			'scheduled_games' : scheduled_games,
		        'USER_LOGGED_IN': request.user.is_authenticated,
			'logged_in_user' : logged_in_user,
			'user' : user,
			'form' : form, 
			'post_success' : post_success, 
			'form_error' : form_error
		}, context_instance=RequestContext(request)
	)

#function for handling the game page
def games(request):

	team = 'team sport'
	individual = 'individual'
	fitness = 'fitness'
	other = 'other'
	team_games = Game.objects.filter(game_type__icontains=team)
	individual_games = Game.objects.filter(game_type__icontains=individual)
	fitness_games = Game.objects.filter(game_type__icontains=fitness)
	other_games = Game.objects.filter(game_type__icontains=other)
	game_post_success = ''
	game_form_error = ''
	user = ''
	USER_LOGGED_IN = ''
	logged_in_user = ''
	m = ''
	rules_error = ''
	vid_error = ''

	if request.user.is_authenticated():
		try:
			user = request.user.facebook_profile
			logged_in_user = User.objects.get(username__exact=user.facebook_id)
		except:
			pass	

	if request.method == 'POST':
		game_form = GameForm(request.POST)
		temp_game_form = game_form.save(commit=False)

		if "wiki" in temp_game_form.rules_url:
			
			if not "http://" in temp_game_form.rules_url:
				temp_game_form.rules_url = "http://" + temp_game_form.rules_url
		else:
			rules_error = 1

		if "youtube.com" in temp_game_form.video_url or "youtu.be" in temp_game_form.video_url:
			if "youtube.com" in temp_game_form.video_url:
				m = re.search('(?<==)\w+', temp_game_form.video_url)
				temp_game_form.video_url = m.group(0)
			else:
				m = re.search('(?<=youtu.be/).*', temp_game_form.video_url)
				temp_game_form.video_url = m.group(0)	
		else:
			vid_error = 1

       		if game_form.errors:
			game_form_error = 1
		elif game_form.is_valid and not rules_error and not vid_error:
			temp_game_form.save()	
			game_post_success = 1
		else:
			game_form_error = 1
    	else:
		game_form = GameForm()
    	return render_to_response('page_templates/game_template.html', 
		{
		
		        'USER_LOGGED_IN': request.user.is_authenticated,
			'user' : user,
			'rules_error' : rules_error,
			'vid_error' : vid_error,
			'logged_in_user' : logged_in_user,
			'game_form' : game_form, 
			'game_post_success' : game_post_success, 
			'game_form_error' : game_form_error,
			'team_games' : team_games, 
			'individual_games' : individual_games, 
			'fitness_games' : fitness_games, 
			'other_games' : other_games
		}, context_instance=RequestContext(request)
	)

#function for handling the community page
def community(request):
	USER_LOGGED_IN = ''
	user = ''
	logged_in_user = ''
	joined_games = ''
	leaving_game = request.GET.get('m','')
	

	if request.user.is_authenticated():
		try:
			user = request.user.facebook_profile
			logged_in_user = User.objects.get(username__exact=user.facebook_id)
			if leaving_game:
				Membership.objects.filter(user__username__exact=user.facebook_id).get(scheduled_game__unique__exact=leaving_game).delete()
			joined_games = Membership.objects.filter(user__username__exact=user.facebook_id)
			
		except:
			pass	

	return render_to_response('page_templates/community_template.html', 
		{
		
		        'USER_LOGGED_IN': request.user.is_authenticated,
			'logged_in_user' : logged_in_user,
			'user' : user,
			'joined_games' : joined_games,
		}, context_instance=RequestContext(request)
	)

def game_page(request, name):

	user = ''
	USER_LOGGED_IN = ''
	game = Game.objects.get(name__exact=name)
	logged_in_user = ''
	if request.user.is_authenticated():
		try:
			user = request.user.facebook_profile
			logged_in_user = User.objects.get(username__exact=user.facebook_id)

		except:
			pass

	return render_to_response('page_templates/game_page_template.html', 
		{
		        'USER_LOGGED_IN': request.user.is_authenticated,
			'logged_in_user' : logged_in_user,
			'user' : user,
			'game' : game,
		}, context_instance=RequestContext(request)
	)
#for facebook
def xd_receiver(request):
	return render_to_response('page_templates/xd_receiver.html')

def profile(request):
	user = ''

	if request.user.is_authenticated():
		user = request.user.facebook_profile
		friendList = request.user.facebook_profile.get_friends_profiles()
	else:
		print "REDIRECTING"
		return HttpResponseRedirect("/")
	
	return render_to_response(
		"page_templates/home_template.html",
		{
		
		    'USER_LOGGED_IN': request.user.is_authenticated,
			'user' : user,
			'USER_LOGGED_IN': request.user.is_authenticated(),
			'user' : user,
			'friendList': friendList,
		},		
		context_instance=RequestContext(request)
		)
